import camelCase from 'camelcase';
import _ from 'lodash';
import PropTypes from 'prop-types';
import React, { Component } from 'react';
import { connect } from 'react-redux';
import {
  View,
  StyleSheet,
  TouchableOpacity,
  Text,
  FlatList,
  Image,
  SafeAreaView, RefreshControl, Dimensions
} from "react-native";
import { Popup, Utils, Notification, BrickButton, TopBar } from 'tuya-panel-kit';
import TYSdk from '../../api';
import GridLayout from '../../components/GridLayout';
import dpCodes from '../../config/dpCodes';
import Strings from '../../i18n';
import icons from '../../res/iconfont.json';
import Res from '../../res';
import { store } from '../../redux/configureStore';
import { debounce } from '../../utils';
import SwitchButton from '../../components/SwitchButton';
import { commonApi } from '@tuya/tuya-panel-api';
import style from "../../config/style";
import { timer } from "rxjs";

const { isIphoneX, convertX: cx, convertY: cy, viewWidth } = Utils.RatioUtils;

const TYDevice = TYSdk.device;
const TYNative = TYSdk.native;

const { } = dpCodes;

class LightTimerScene extends Component {
  static defaultProps = {
    dpState: {},
  };

  constructor(props) {
    super(props);

    this.state = {
      timers: null,
      devID: null,
      devType: '0',
      isEditing: false,
      isShowNodata: false,
      refreshing: false,
    };
  }

  async componentDidMount() {
    try {
      // 获取定时列表
      this.refreshData();

      TYSdk.device.getDeviceInfo().then(res => {
        const { devId, groupId } = res;
        this.setState({
          devID: groupId || devId,
          devType: groupId ? 1 : 0,
        });
      });
    } catch (err) {
      console.warn(err);
    }
  }

  refreshData = debounce(async () => {
    const timersArr = await TYSdk.getTimerList('light');

    let isShowNodata = false;
    if (timersArr.length === 0) {
      isShowNodata = true; //'定时列表为空';
    }
    this.setState({
      timers: timersArr,
      isShowNodata: isShowNodata,
      isEditing: false,
    });
  });

  onRefresh = debounce(async () => {

    this.setState({refreshing: true});

    const timersArr = await TYSdk.getTimerList('light');

    setTimeout(() => {
      // 2秒后执行的代码
      console.log('2秒已过，执行操作');
      // 你可以在这里执行你的代码，比如更新state或者导航到另一个页面
      this.setState({
        timers: timersArr,
        isShowNodata: timersArr.length === 0,
        isEditing: false,
        refreshing: false,
      });
    }, 2000);

  });

  addClick = debounce(() => {
    const { timers } = this.state;
    console.log('传参timers', timers);
    TYSdk.Navigator.push({
      id: 'lightTimerEdit',
      timerList: timers,
      isNeedRefresh: need => {
        // 添加定时，刷新界面
        console.log('need refresh', need);
        if (need) {
          this.refreshData();
        }
      },
    });
  });

  editTimerClick = debounce((timer) => {
    const { timers } = this.state;
    TYSdk.Navigator.push({
      id: "lightTimerEdit",
      timerList: timers,
      isEditTimer: true,
      timer: timer,
      isNeedRefresh: ( need ) => {
        // 添加定时，刷新界面
        console.log('need refresh', need);
        if (need){
          this.refreshData();
        }
      },
    });
  });

  delClick = debounce(() => {
    const { devID, devType, timers } = this.state;

    let ids = '';
    timers.forEach(timer => {
      if (timer.isSel) {
        ids = ids + ',' + timer.id;
        if (timer.endTimeId) {
          ids = ids + ',' + timer.endTimeId;
        }
      }
    });
    if (ids.length > 1) {
      ids = ids.slice(1);
    } else return;

    console.log(ids);

    console.log(devID, devType);
    commonApi.timerApi
      .modDeleteTaskByIds({
        bizId: devID,
        bizType: devType,
        ids: ids, // 定时任务id
        status: 2,
      })
      .then(async response => {
        console.log(response);
        // 获取定时列表
        this.refreshData();
      })
      .catch();
  });

  switchBtnClick = debounce((v, item, index) => {
    const { devID, devType, timers } = this.state;
    console.log(devID, devType, item.id, v);
    let ids = item.id;
    if (item.endTime) {
      ids = ids + ',' + item.endTimeId;
    }
    commonApi.timerApi
      .modDeleteTaskByIds({
        bizId: devID,
        // 根据 getDevInfo 判断是否存在 groupId。若存在，则为群组设备，否则为单设备
        bizType: devType,
        ids: ids, // 定时任务的 id
        status: v ? 1 : 0, // 当前定时状态
      })
      .then(response => {
        console.log(response);
        item.status = item.status === 1 ? 0 : 1;
        timers[index] = item;
        this.setState({
          timers,
        });
      })
      .catch();
  });

  cellView(item, index) {
    const weekdaysStr = TYSdk.changeToWeekdays(item.loops);
    const timeStr = item.endTime == null ? item.time : `${item.time} ~ ${item.endTime}`;
    const { timers, isEditing } = this.state;
    const name = TYSdk.timerName(item.aliasName);




    return (
      <TouchableOpacity
        style={styles.cell}
        onPress={() => {
          if (isEditing) {
            timers[index].isSel = !timers[index].isSel;
            this.setState({ timers });
          }else {
            this.editTimerClick(item);
          }
        }}
      >
        <View style={styles.tips}>
          <View style={styles.twoLines}>
            <Text style={styles.cellTitle}>{timeStr}</Text>
            <Text style={[styles.cellTitle, { fontWeight: 'normal', fontSize: 13, marginTop: 5 }]}>
              {`${name} | ${weekdaysStr}`}
            </Text>
          </View>
        </View>

        {/* 定时开关 */}
        {!isEditing ? (
          <SwitchButton
            style={{ marginRight: 20, marginTop: 5 }}
            value={item.status === 1}
            onValueChange={v => {
              this.switchBtnClick(v, item, index);
            }}
          />
        ) : null}

        {/* 编辑状态下多选 勾选图标 */}
        {isEditing ? (
          <Image
            style={{ marginRight: 20, marginTop: 5, width: 30, height: 30 }}
            source={timers[index].isSel ? Res.fsel : Res.funsel}
            resizeMode="cover"
          />
        ) : null}
      </TouchableOpacity>
    );
  }

  addBtn() {
    return (
      <View
        style={{
          backgroundColor: '#FFFFFF',
          height: 86,
          flexDirection: 'row',
          alignItems: 'center',
          justifyContent: 'flex-end',
          marginRight: 30,
          marginBottom: 40,
          marginTop: 0,
        }}
      >
        <TouchableOpacity
          style={styles.addBtn}
          onPress={() => {
            this.addClick();
          }}
        >
          <View style={styles.addBtn}>
            <Image style={styles.addBtnIcon} source={Res.iconAdd} resizeMode="center" />
          </View>
        </TouchableOpacity>
      </View>
    );
  }

  delBtn() {
    return (
      <View
        style={{
          backgroundColor: '#FFFFFF',
          height: 80,
          flexDirection: 'column',
          alignItems: 'center',
          justifyContent: 'space-between',
          marginBottom: 20,
          paddingTop: 20,
        }}
      >
        {/* "删除" */}
        <BrickButton
          text={Strings.delete}
          textStyle={{ fontSize: 15 }}
          wrapperStyle={{ backgroundColor: '#20AEE5' }}
          onPress={() => {
            this.delClick();
          }}
        />
      </View>
    );
  }

  nodataView() {
    const { isShowNodata } = this.state;
    return (
      <View
        style={{
          // backgroundColor: '#b4dcec',
          height: 80,
          width: 80,
          flexDirection: "column",
          alignItems: "center",
          justifyContent: "center",
          position: 'absolute',
          marginTop: Dimensions.get('window').height*0.4-40,
          marginLeft: Dimensions.get('window').width*0.5-40,
        }}
      >
        <Image style={{}} resizeMode="cover" source={Res.iconPageNodataTimerLight} />
        <Text style={{ fontSize: 14, color: '#939494' }}>{Strings.list_empty_title_timer}</Text>
      </View>
    );
  }

  listView(timers, renderItem) {
    const { refreshing } = this.state;
    return (
      <FlatList
        // style={{ height: 200 }}
        data={timers}
        renderItem={renderItem}
        keyExtractor={(item, index) => index.toString()}
        refreshControl={
          <RefreshControl
            refreshing={refreshing}
            onRefresh={this.onRefresh}
            colors={['blue', 'green', 'red']} // 可以定义刷新进度条的颜色
            tintColor="gray" // 刷新进度条的颜色
            title={Strings.card_loading}// 下拉时显示的文本
            titleColor="#999999" // 文本的颜色
          />
        }
      />
    );
  }

  topView() {
    const { timers, isEditing, isShowNodata } = this.state;
    return (
      <TopBar.Container
        backgroundColor="#ac4545"
        style={{ height: TopBar.height }}
        contentStyle={{ height: TopBar.height, marginTop: 10 }}
      >
        <TopBar.Action
          size={20}
          name="backIos"
          color="#4C4C4C"
          onPress={() => TYSdk.Navigator.pop()}
        />
        <TopBar.Content />
        <TopBar.Action
          source={Res.fedit}
          color="#4C4C4C"
          size={20}
          style={{ marginTop: 500 }}
          onPress={() => {
            // 点击右上角进入、退出编辑状态
            if (isEditing) {
              timers.forEach(timer => {
                timer.isSel = false;
              });
            }
            if (!isShowNodata) {
              this.setState({ isEditing: !this.state.isEditing });
            }
          }}
        />
      </TopBar.Container>
    );
  }

  topEditing() {
    return (
      <TopBar.Container
        background="#FFFFFF"
        style={{ height: TopBar.height }}
        contentStyle={{ height: TopBar.height, marginTop: 10 }}
      >
        <TopBar.Action
          size={20}
          name="backIos"
          color="#4C4C4C"
          onPress={() => TYSdk.Navigator.pop()}
        />
        <TopBar.Content />
        <TopBar.Action
          source={Res.fclose}
          color="#4C4C4C"
          size={20}
          style={{ marginTop: 500 }}
          onPress={() => {
            // 点击右上角进入、退出编辑状态
            this.setState({ isEditing: !this.state.isEditing });
          }}
        />
      </TopBar.Container>
    );
  }

  render() {
    const { timers, isEditing, isShowNodata } = this.state;

    const renderItem = ({ item, index }) => this.cellView(item, index);

    return (
      <View style={[styles.container]}>
        {!isEditing ? this.topView() : null}

        {isEditing ? this.topEditing() : null}

        <View style={{ flex: 1, flexDirection: 'column', justifyContent: 'space-between' }}>
          {/* 灯光定时 */}
          <Text style={{
            paddingTop: 40,
            paddingBottom: 40,
            paddingLeft: 30,
            fontSize: 30,
            color: "#333333",
            // backgroundColor: "#b4dcec"
          }}>
            {Strings.page_title_timer_list_light}
          </Text>


          {/* 定时列表 */}
          { this.listView(timers, renderItem) }
          { isShowNodata ? this.nodataView() : null}

          {!isEditing ? this.addBtn() : null}

          {isEditing ? this.delBtn() : null}
        </View>

      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    flexDirection: 'column',
    // justifyContent: 'space-between',
  },
  tips: {
    justifyContent: 'space-between',
    flexDirection: 'row',
  },
  cell: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
    backgroundColor: '#fff',
    height: 60,
    marginStart: 30,
    marginEnd: 10,
    marginTop: 10,
    // width: '100%',
    borderRadius: 12,
  },
  oneLine: {
    flexDirection: 'row',
    alignItems: 'stretch',
  },
  twoLines: {
    flexDirection: 'column',
    alignItems: 'stretch',
  },
  cellTitle: {
    fontSize: 16,
    fontWeight: 'bold',
    color: '#000',
  },
  icon: {
    justifyContent: 'center',
    marginStart: 20,
    width: 40,
    height: 40,
  },
  floatingContainer: {
    // 悬浮右下角
    position: 'absolute',
    right: 30,
    bottom: 50,
    width: 50,
    height: 50,
    justifyContent: 'center',
    alignItems: 'center',
    borderRadius: 25,
  },
  addBtn: {
    marginRight: 0,
    width: 50,
    height: 50,
    borderRadius: 25,
    backgroundColor: '#22a8dc',
    justifyContent: 'center',
    alignItems: 'center',
  },
  addBtnIcon: {
    width: 50,
    height: 50,
  },
});

export default connect(({ dpState }) => ({
  dpState,
}))(LightTimerScene);
